package com.spring.service;

import com.spring.config.BeanPostProcessor;
import com.spring.context.Component;
import com.spring.context.HscValue;

import java.lang.reflect.Field;

/**
 * 做一个增强器，用作给对象的属性做赋值操作
 */
@Component //交给容器进行管理
public class HscValueBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) {
        System.out.println(bean.getClass().getName() + "调用了HscValueBeanPostProcessor前置增强方法.......");
        //获取当前的类所有的数下
        for (Field field : bean.getClass().getDeclaredFields()) {
            if (field.isAnnotationPresent(HscValue.class)) {
                field.setAccessible(true);
                try {
                    field.set(bean,field.getAnnotation(HscValue.class).value());
                    System.out.println("自定义扩展：自定义HscValueBeanPostProcessor实现BeanPostProcessor接口，完成通过增强器进行实现，对注解上的value值直接付给属性，value值为："+field.getAnnotation(HscValue.class).value());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return bean;
    }
}
